<?php

namespace app\api2\controller;

use \app\common\controller\Api;
use app\common\library\Token;
use EasyWeChat\Factory;
use fast\Random;
use think\Exception;
use think\Log;
use \think\Validate;
use app\common\library\Sms;
use \think\Cache;


use \think\Db;


class Order extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $needWorkerLogin = ['getOrder', 'getDetail', 'complete'];
    protected $miniConfig = [
        'app_id' => 'wxb2f4f9b7e792c428',
        'secret' => '652aa06f7ac713b380eed4d3bc008cae',
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',
        //...
    ];

    /**
     * 获取订单列表
     * @throws \think\exception\DbException
     */
    public function getOrder()
    {
        if ($this->request->isPost()) {
            $status = trim($this->request->post('status'));
            $page = trim($this->request->post('page'));

            $data = (array)$this->_data;

            if (!$status || !$page) {
                $this->success('缺少必要参数', [], 201);
            }
            if ($status == 4) {

                $orderList = Db::table('fa_order')
                    ->field('id,service_name,area,main_image,cost_price,pay_price,appointmenttime,status,unit_price')
                    ->where('worker_id', $data['user_id'])
                    ->whereIn('status', '4,5')
                    ->order('createtime desc')
                    ->paginate(5, false, ['page' => $page]);

                $this->success('ok', ['orderList' => $orderList->items(), 'total' => $orderList->total()], 200);
            }
            $orderList = Db::table('fa_order')
                ->field('id,service_name,area,main_image,cost_price,pay_price,appointmenttime,status,unit_price')
                ->where('status', $status)
                ->where('worker_id', $data['user_id'])
                ->order('createtime desc')
                ->paginate(5, false, ['page' => $page]);

            $this->success('ok', ['orderList' => $orderList->items(), 'total' => $orderList->total()], 200);
        }
    }


    /**
     *
     * 获取订单详情
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function getDetail()
    {
        if ($this->request->isPost()) {

            $id = trim($this->request->post('id'));
            $data = (array)$this->_data;

            if (!$id) {
                $this->success('缺少必要参数', [], 201);
            }
            // 联查小区表(省，市，区，小区)
            $order = Db::table('fa_order')
                ->alias('a')
                ->field('a.*,c.province,c.city,c.districts,c.village')
                ->join('fa_village c', 'c.id=a.village_id')
                ->where('a.id', $id)
                ->where('worker_id', $data['user_id'])
                ->whereOr('worker_id', 'like', ' %,' . $data['user_id'])
                ->whereOr('worker_id', 'like', $data['user_id'] . ',%')
                ->whereOr('worker_id', 'like', '%,' . $data['user_id'] . ',%')
                ->find();

            if (!$order) {

                $this->success('未查询到订单', [], 201);

            }
            //若使用优惠券联查优惠券表(title,fee)，没有使用则自己给结果添加字段title="未使用优惠券",fee='0.00'
            $order['fee'] = 0.00;
            $order['title'] = '未使用优惠券';

            if ($order['user_coupon_id']) {
                $userCoupon = Db::table('fa_user_coupon')
                    ->field('coupon_id')
                    ->where('id', $order['user_coupon_id'])
                    ->find();
                $coupon = Db::table('fa_coupon')
                    ->field('fee,title')
                    ->where('id', $userCoupon['coupon_id'])
                    ->find();
                if ($coupon) {
                    $order['fee'] = $coupon['fee'];
                    $order['title'] = $coupon['title'];
                }

            }
            //根据订单的workerid查询员工表(员工id,头像，员工姓名,年龄，手机号，评分)
            $workerIds = explode(",", $order['worker_id']);

            $workerList = [];

            foreach ($workerIds as $key => $workerId) {
                $workerList[$key] = Db::table('fa_worker')
                    ->field(['id', 'avatar', 'name', 'age', 'score', 'mobile'])
                    ->where('id', $workerId)
                    ->find();
            }

            $this->success('ok', ['order' => $order, 'workerList' => $workerList], 200);
        }
    }


    /**
     * 完成订单
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\Exception
     */
    public function complete()
    {
        if ($this->request->isPost()) {

            $id = trim($this->request->post('id'));
            $data = (array)$this->_data;

            if (!$id) {
                $this->success('缺少必要参数', [], 201);
            }

            //查询条件为where(worker_id=worker_id,订单id=id status=1)

            $order = Db::table('fa_order')
                ->where('id', $id)
                ->where('worker_id', $data['user_id'])
                ->where('status', 1)
                ->whereOr('worker_id', 'like', ' %,' . $data['user_id'])
                ->whereOr('worker_id', 'like', $data['user_id'] . ',%')
                ->whereOr('worker_id', 'like', '%,' . $data['user_id'] . ',%')
                ->find();

            if (!$order) {

                $this->success('未查询到订单', [], 201);
            }

            Db::startTrans();

            $bank = Db::table('fa_worker_bank')
                ->where('worker_id', $data['user_id'])
                ->lock(true)
                ->find();

            if (!$bank) {
                Db::commit();
                $this->success('未绑定银行卡', [], 201);
            }
            try {
                //修改此订单状态为已完成
                $completetime = time();

                Db::table('fa_order')
                    ->where('id', $id)
                    ->update([
                        'status' => 2,
                        'completetime' => $completetime
                    ]);

                //写入资金记录表fa_worker_money_log
                Db::table('fa_worker_money_log')
                    ->insert([
                        'worker_id' => $data['user_id'],
                        'type' => 1,
                        'money' => $order['pay_price'],
                        'before' => $bank['balance'],
                        'after' => $bank['balance'] + $order['pay_price'],
                        'order_id' => $id,
                        'memo' => $order['remark'] ? $order['remark'] : '',
                        'createtime' => time()
                    ]);

                //增加员工资金
                Db::table('fa_worker_bank')
                    ->where('worker_id', $data['user_id'])
                    ->update(['balance' => $bank['balance'] + $order['pay_price']]);

                //已服务数量+1
                Db::table('fa_worker')
                    ->where('id', $data['user_id'])
                    ->setInc('service_count');

                Db::commit();

            } catch (Exception $ex) {
                Db::rollback();
                Log::error($ex);
                $this->success($ex->getMessage(), [], 201);
            }

            $openid = Db::table('fa_user')
                ->where('id', $order['user_id'])
                ->value('openid');

            if (!$openid) {
                $this->success('未查询到用户openid', [], 201);
            }
            //下发订阅消息给用户
            $data = [
                'template_id' => 'OaMAsPeKmlKQDdUAv-MTDild0bRaOZ6iawSqLLsuXwE', // 所需下发的订阅模板id
                'touser' => $openid,     // 接收者（用户）的 openid
                'page' => '/pages/order/detail?id=' . $id,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'character_string5' => [
                        'value' => $order['id'],
                    ],
                    'thing6' => [
                        'value' => $order['service_name'],
                    ],
                    'amount11' => [
                        'value' => '￥' . $order['pay_price'],
                    ],
                    'date9' => [
                        'value' => date('Y-m-d H:i', $completetime),
                    ],
                    'thing16' => [
                        'value' => '本次服务已完成，祝您生活愉快！',
                    ],
                ],
            ];


            $mini = Factory::miniProgram($this->miniConfig);

            $mini->subscribe_message->send($data);

            $this->success('ok', [], 200);
        }
    }
}